//https://leetcode.cn/problems/reverse-words-in-a-string/
package codeRandomThoughts.Test151反转字符串中的单词;

import java.util.Arrays;

public class Solution {
    public String reverseWords(String s) {
        //首先要对空格进行处理 使用快慢指针
        char[] chars = s.toCharArray();
        int slow = 0;
        int fast = 0;
        while (fast < chars.length) {
            if (chars[fast] != ' ') {
                chars[slow] = chars[fast];
                fast++;
                slow++;
            } else if (slow > 0 && chars[fast] == ' ') {
                while (fast < chars.length && chars[fast] == ' ') {
                    fast++;
                }
                if (fast!=chars.length){
                    chars[slow] = ' ';
                    slow++;
                }
            } else {
                fast++;
            }
        }
        char[] trimChars = Arrays.copyOfRange(chars, 0, slow);

        //其实很简单,先反转整个字符串,再单独反转单词即可
        reverseArray(trimChars, 0, trimChars.length - 1);

        //反转单词
        for (int i = 0; i < trimChars.length; ) {
            for (fast = i; fast < trimChars.length; fast++) {
                if (trimChars[fast] == ' ')
                    break;
            }
            reverseArray(trimChars, i, fast - 1);
            if (fast == trimChars.length) {
                break;
            }
            i = fast + 1;
        }
        return new String(trimChars);
    }

    void reverseArray(char[] array, int begin, int end) {
        char tem = ' ';
        while (end > begin) {
            tem = array[begin];
            array[begin] = array[end];
            array[end] = tem;
            begin++;
            end--;
        }
    }
}
